import { useEffect, useState } from "react";
import { SelectGroup } from "@/components/func";
import { getQrGroup, addQrGroup } from "@/assets/js/networkRequest/method";

interface props {
  qrGroupId: number; // 选择的分组id
  setQrGroupId: any; // 设置选择的分组id
}

let order: number = 0;
let listGroupData: any = [];

const QrGroup = ({ qrGroupId, setQrGroupId }: props) => {
  const [, setRender] = useState(0);

  /* 每次对列表数据处理之后进行一次初始化操作 */
  const initListData = () => {
    listGroupData.sort((a: any, b: any) => {
      return a.order - b.order;
    });
    // 保存下一个添加分组时需要的排序号
    order = listGroupData[listGroupData.length - 1].order + 1;
    setRender(Math.random() + 1);
  };

  useEffect(() => {
    (async () => {
      await getQrGroup().then((res: any) => {
        console.log(res);
        if (res.code === 200) {
          listGroupData = res.data;
          initListData();
        }
      });
    })();
  }, []);
  return (
    <div className="flex items-center mb-24">
      <div className="flex items-center">
        <span className="title-item w-106 text-right mr-16">
          <span className="text-red-defalut relative top-4 text-lg">*</span> 选择分组:
        </span>
        <SelectGroup
          domId="area"
          qrGroupId={qrGroupId}
          setQrGroupId={setQrGroupId}
          listGroupData={listGroupData}
          onPressEnter={async e => {
            await addQrGroup({ name: e, order }).then((res: any) => {
              if (res.code === 200) {
                listGroupData.push({ ...res.data, count: 0 });
                initListData();
              }
            });
          }}
        />
      </div>
    </div>
  );
};

export default QrGroup;
